package leetcode;

import java.util.LinkedList;
import java.util.Queue;

public class code98 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public static void main(String[] args) {
        Integer[] arrayA = new Integer[]{5,4,6,null,null,3,7};
        TreeNode root = buildtree(arrayA);
        System.out.println(isValidBST(root));
    }

    public static boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public static boolean isValidBST(TreeNode root, long min, long max) {
        if (root == null)
            return true;
        if (root.val <= min || root.val >= max)
            return false;
        return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
    }

    public static TreeNode buildtree(Integer[] arrayA){
        if (arrayA==null||arrayA.length==0)
            return null;
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(arrayA[0]);
        queue.add(root);
        int i = 1;
        while(!queue.isEmpty()&&i<arrayA.length){
            TreeNode currentNode = queue.poll();
            if(i<arrayA.length && arrayA[i]!=null){
                currentNode.left = new TreeNode(arrayA[i]);
                queue.offer(currentNode.left);

            }
            i++;
            if (i < arrayA.length && arrayA[i] != null){
                currentNode.right = new TreeNode(arrayA[i]);
                queue.offer(currentNode.right);

            }
            i++;
        }
        return root;
    }

}
